﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;

namespace comm
{
    public static class ThreadHelper
    {
        static UniqueID _uid = new UniqueID();
        static Dictionary<string, Thread> _thDic = new Dictionary<string, Thread>();

        public static void StopAll()
        {
            lock (_thDic)
            {
                foreach (var th in _thDic.Values)
                {
                    try
                    {
                        th.Abort();
                    }
                    catch (Exception)
                    {
                    }
                }
                _thDic.Clear();
            }
        }
        public static void Stop(string threadId)
        {
            lock (_thDic)
            {
                if (_thDic.ContainsKey(threadId))
                {
                    _thDic[threadId].Abort();
                    _thDic.Remove(threadId);
                }
            }
        }
        public static string Run(Action callback)
        {
            var id = _uid.NewId();
            var th = new Thread(new ThreadStart(callback));
            th.Start();
            lock (_thDic)
            {
                _thDic.Add(id, th);
            }
            return id;
        }
    }
}
